//
//  StatusCellPictureView.swift
//  微博个人swift
//
//  Created by 李灏 on 16/2/20.
//  Copyright © 2016年 lh. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

//注册cell的id
private let pictureCellId = "pictureCellId"

class StatusCellPictureView: UICollectionView {
    //外部变量获取图片url数组
    var imageURLs:[NSURL]? {
        didSet {
            //计算配图大小
            let pSize = caclePictureViewSize()
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(pSize)
            }
            testLabel.text = "\(imageURLs?.count ?? 0)"
            //更新数据后一定要刷新
            reloadData()
        }
    }
    
    /*
    单图会按照图片等比例显示
    多图的图片大小固定
    多图如果是4张，会按照 2 * 2 显示
    多图其他数量，按照 3 * 3 九宫格显示
    */
    private func caclePictureViewSize() -> CGSize {
        let imageCount = imageURLs?.count ?? 0
        //没有配图
        if imageCount == 0{
            return CGSizeZero
        }
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //一张图
        if imageCount == 1{
            //等比例显示图片
            //TODO: 暂时写死
            var itemSize = CGSizeMake(180, 120)
            let key = imageURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            if image != nil {
                itemSize = image.size
            }
            
            layout.itemSize = itemSize
            return itemSize
        }
        //
        let itemWidth = (KWidth - StatusCellMargin*2 - pictureMargin*2)/3
        //设置多图的itemSize
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        //如果四张图2*2
        if imageCount == 4{
            let w = itemWidth*2 + pictureMargin
            return CGSizeMake(w, w)
        }
        //程序走到这里  2, 3, 5,6,7,8,9
        /*
        1,2,3   ==> 1
        4,5,6   ==> 2
        7,8,9   ==> 3
        */
        //确定数字分布
        let row = CGFloat((imageCount - 1)/3 + 1)
        
        //计算最大宽度
        let maxW = itemWidth * 3 + 2 * pictureMargin
        let maxH = itemWidth * row + (row - 1) * pictureMargin

        return CGSizeMake(maxW, maxH)
        
    }
    override init(frame: CGRect,collectionViewLayout layout: UICollectionViewLayout) {
        //布局对象设置
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = pictureMargin
        layout.minimumLineSpacing = pictureMargin
        super.init(frame:frame,collectionViewLayout: layout)
        setupUI()
        self.scrollsToTop = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置视图
    private func setupUI() {
        // Register cell classes
        registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellId)
        self.dataSource = self
        self.delegate = self
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    //MARK: 懒加载子视图
    private lazy var testLabel: UILabel = UILabel(text: "", fontSize: 40, textColor: UIColor.redColor())
  
}
extension StatusCellPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    // MARK: UICollectionViewDataSource
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellId, forIndexPath: indexPath) as! PictureCell
        cell.imageURL = imageURLs![indexPath.item]
        // indexPath.item % 2 取奇数偶数
        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.purpleColor() : UIColor.yellowColor()
        return cell
    }
    
    //点击cell的方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = self.imageURLs?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
//        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
//        
//        browser.sourceImagesContainerView = 原图的父控件;
//        
//        browser.imageCount = 原图的数量;
//        
//        browser.currentImageIndex = 当前需要展示图片的index;
//        
//        browser.delegate = 代理;
//        
//        [browser show]; // 展示图片浏览器
//        2.实现代理方法
//        
//        // 返回临时占位图片（即原来的小图）
//        
//        (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index { ； }
//        // 返回高质量图片的url
//        
//        (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index { ； }


    }
}
extension StatusCellPictureView: SDPhotoBrowserDelegate {
    //返回高质量图片 字符串的替换
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //获取当前url对应的urlString
        if let url = imageURLs?[index] {
            //将urlString 中的 thumbnail 替换为 bmiddle
            let urlString = url.absoluteString
            let str = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
            //转换为NSURL兑现返回
            return NSURL(string: str)

        }
        return nil
    }
        //// 返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        //返回cell的image对象
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        //获取用户点击的Cell
        if let cell = self.cellForItemAtIndexPath(indexPath) as? PictureCell {
            return cell.iconView.image
        }
        return nil
    }
}
//自定义cell
class PictureCell: UICollectionViewCell {
    //外部变量
    var imageURL:NSURL?{
        didSet {
            //设置url
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            //长宽高都约束
            make.edges.equalTo(contentView.snp_edges)
        }
        
    }
    //懒加载视图
    private lazy var iconView:UIImageView = {
        let v = UIImageView()
        //视图内容显示模式 默认显示 是 ContentModeScaleToFill   ==> 缩放进行填充  比例一致的图片使用这种样式显示
        //.ScaleAspectFit 图片显示上下可能会留白  基本不会使用这样显示样式
        //ScaleAspectFill 视图会被剪裁  但是 图片显示不会失真  并且不会留白
        v.contentMode = .ScaleAspectFill
        //裁剪 手写代码不会自动裁剪
        v.clipsToBounds = true
        return v
    }()
}
